package com.example.mq.mqServer.core;

import com.example.mq.common.ConsumerEnv;
import com.example.mq.mqServer.util.JsonUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @BelongsProject: 0.mq
 * @BelongsPackage: com.example.mq.mqServer.core
 * @Author : 游在海里的鱼
 * @CreateTime : 2023-11-22  12:04
 * @Version : 1.0
 * @Description : MQ中的消息队列,MSG = message
 */
@Data
public class MSGQueue {
    //队列的身份标识
    private String name;
    //是否持久化
    private boolean durable;
    //是否自动删除（有使用吗）
    private boolean autoDelete;
    //独有的，true表示此队列只能由一个消费者使用，false则是都可以使用（暂无实现）
    private boolean exclusive;
    //创建队列时，一些额外的参数选项（此功能暂无实现）
    private Map<String,Object> arguments;

    //消费者列表
    private List<ConsumerEnv> consumerEnvList =new ArrayList<>();
    //消费者次序，到第几个消费者了
    private AtomicInteger consumerSeq = new AtomicInteger(0);


    public MSGQueue(){

    }

    public MSGQueue(String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments) {
        this.name = name;
        this.durable = durable;
        this.exclusive = exclusive;
        this.autoDelete = autoDelete;
        this.arguments = arguments;
    }

    /*------------------------------------普--通--方--法------------------------------------------------------------------
     * @Desc  : 添加消费者
     * @Param : [consumerEnv]
     * @Return: void
    **/
    public void addConsumerEnv(ConsumerEnv consumerEnv){
            consumerEnvList.add(consumerEnv);
    }

    /*------------------------------------普--通--方--法------------------------------------------------------------------
     * @Desc  : 轮询选择消费者
     * @Param : []
     * @Return: com.example.mq.common.ConsumerEnv
    **/
    public ConsumerEnv chooseConsumer(){
        if(consumerEnvList.size() == 0){
            return null;
        }
        int index = consumerSeq.get() % consumerEnvList.size();
        //自增++
        consumerSeq.getAndIncrement();
        return consumerEnvList.get(index);
    }

    //json与map的互转
    public String getArguments() {
        try {
            return JsonUtils.getJson(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setArguments(String arguments) {
        try {
            this.arguments = JsonUtils.setSrc(arguments, new TypeReference<HashMap<String, Object>>(){});
            return;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        this.arguments = null;
    }
    public Object getArgumentsValue(String key){
        return arguments.get(key);
    }

    public void setArgumentsKey_Value(String key,Object value){
        arguments.put(key, value);
    }
}
